package com.jt.tenant.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetLoginAdmin;
import com.jt.tenant.conn.GetRegisterUser;
import com.jt.tenant.conn.GetResetPassword;
import com.jt.tenant.widget.Tools;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


/**
 * Created by Administrator on 2016/2/24.
 */
public class Register2Activity extends JTActivity implements View.OnClickListener {

    private TextView tv_register_1, tv_register_2, tv_register_3;

    private TextView title_name, go_next;

    private EditText new_pwd, new_pwd2;

    private ImageView clear_pwd1, clear_pwd2;

    private String pwd_str1;

    private String phone;

    private SharedPreferences.Editor editor;

    private SharedPreferences preferences;

    private int login_type;//模式，0：注册，1:微信登录创建账号 ，2：QQ登录创建账号,3：重置密码，

    private String account;//三方账号

    private String auth_code;//验证码

    private GetRegisterUser getRegisterUser = new GetRegisterUser(new AsyCallBack<GetRegisterUser.Info>() {

        @Override
        public void onSuccess(String toast, int type, GetRegisterUser.Info info) throws Exception {

            if (info.msg.equals("000")) {

                JTApplication.jtPreferences.savePhone(phone);

                JTApplication.jtPreferences.saveUserId(info.userId);

                JTApplication.jtPreferences.saveObdId(info.obdId);

                //saveToken
                JTApplication.jtPreferences.saveToken(info.token);

                registerResult();

            }else {

                UtilToast.show(context,info.msg);

            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
        }

    });

    private GetLoginAdmin getLoginAdmin = new GetLoginAdmin(new AsyCallBack<GetLoginAdmin.Info>() {

        @Override
        public void onSuccess(String toast, int type, GetLoginAdmin.Info info) throws Exception {

            if (info.msg.equals("000")) {

                if (!info.user_obdId.equals("") && !info.user_obdId.equals("null")) {

                    JPushInterface.setAliasAndTags(context, info.user_phone, JTApplication.tag, new TagAliasCallback() {

                        @Override

                        public void gotResult(int i, String s, Set<String> set) {

                            Log.e("JPush开启", "Jpush status: " + i);//状态

                        }
                    });

                }

                //无论什么情况都保存账号
                editor.putString("LoginUser", phone).commit();

                editor.putString("LoginPwd", pwd_str1).commit();

                editor.putString("AutoLogin", "yes").commit();

                //存储数据
                JTApplication.jtPreferences.saveUserId(info.userId);

                JTApplication.jtPreferences.saveHaveUid(true);

                //saveObdId

                JTApplication.jtPreferences.saveObdId(info.user_obdId);

                if (!info.user_obdId.equals("") && !info.user_obdId.equals("null")) {

                    JTApplication.jtPreferences.saveHaveObdid(true);

                } else {

                    JTApplication.jtPreferences.saveHaveObdid(false);

                }
//                    //saveToken
                JTApplication.jtPreferences.saveToken(info.session_token);

                Log.e("TAG", "token=" + info.session_token + ",obdid=" + JTApplication.jtPreferences.readOdbID());
                //savePhone
                JTApplication.jtPreferences.savePhone(info.user_phone);
                //nickname
                JTApplication.jtPreferences.saveNickName(info.user_nickname);
                //头像
                JTApplication.jtPreferences.saveHeadPath(info.user_headpic);
                //车牌号
                JTApplication.jtPreferences.savePlateNum(info.car_plateNum);
                //车架号
                JTApplication.jtPreferences.saveVincode(info.car_vincode);
                //车辆id
                JTApplication.jtPreferences.saveCarId(info.car_id);

                //城市编号
                JTApplication.jtPreferences.saveCityCode(info.city_code);

                //机动车号
                JTApplication.jtPreferences.saveEngineCode(info.engine_code);

                //性别
                JTApplication.jtPreferences.saveSex(info.user_sex);

                //车id
                JTApplication.jtPreferences.saveCarId(info.carId);

                //车的归属类型
                JTApplication.jtPreferences.saveCarType(info.carType);

                //车型id
                JTApplication.jtPreferences.saveCategoryId(info.categoryId);

                //城市
                JTApplication.jtPreferences.saveCity(info.city);

                //购买时间
                JTApplication.jtPreferences.saveRemark(info.remark);

                //账号状态
                JTApplication.jtPreferences.saveAccountState(info.account_state);

                JTApplication.jtPreferences.saveBSX(info.bsx);

                JTApplication.jtPreferences.savePP(info.pp);

                JTApplication.jtPreferences.savePL(info.pl);

                JTApplication.jtPreferences.saveNK(info.nk);

                JTApplication.jtPreferences.saveCX(info.cx);

                //传送成功 存储图片路径
                JTApplication.jtPreferences.saveHeadPath(info.user_headpic);

                //存储 紧急账号(没用！！)
//                            JTApplication.jtPreferences.savePhone2(phone);
                //存储 昵称
                JTApplication.jtPreferences.saveNickName(info.user_nickname);

                //存储 WIFI状态
                JTApplication.jtPreferences.saveWIFI(info.wifi);

                //存储 GPS隐私管理
                if (info.gpsType.equals("0")) {

                    JTApplication.jtPreferences.savePrivacy(false);

                } else {

                    JTApplication.jtPreferences.savePrivacy(true);

                }


                //存储 WIFI密码
                JTApplication.jtPreferences.saveWIFIPWD(info.wifipwd);
                //存储 积分
//                    JTApplication.jtPreferences.saveUserIntegral(info.user_integralCount,"1");

                //存储保险状态
                JTApplication.jtPreferences.saveInsFlag(info.baoxianFlag);

                //存储驾驶证号
                JTApplication.jtPreferences.saveDriverNum(info.driverNum);

                //存储有效起始日期
                JTApplication.jtPreferences.saveDriverEffectiveDate(info.driverEffectiveDate);
                //存储有效期
                JTApplication.jtPreferences.saveDriverEffectiveYear(info.driverEffectiveYear);
                //性别
                if (info.user_sex.equals("1")) {

                    JTApplication.jtPreferences.saveSex("男");

                } else if (info.user_sex.equals("2")) {

                    JTApplication.jtPreferences.saveSex("女");

                }

                JTApplication.jtPreferences.saveShockNum(Integer.parseInt(Tools.F_num(info.tCollisionRemindValue)));

                JTApplication.jtPreferences.saveShockBool(Integer.parseInt(Tools.F_num(info.tCollisionRemindIsOpen)));

                for (int i = 0; i < info.personSet.size(); i++) {

                    if (info.personSet.get(i).equals("0")) {

                        JTApplication.jtPreferences.saveMessage(true, String.valueOf(i + 1));

                    } else {

                        JTApplication.jtPreferences.saveMessage(false, String.valueOf(i + 1));

                    }


                }


                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();

                if(login_type == 0){

                    startActivity(new Intent(context, Register3Activity.class));

                }else {

                    startActivity(new Intent(context, MainActivity.class));

                }

                finish();

            } else {

                Toast.makeText(context, info.msg, Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            UtilToast.show(context, "连接超时");

        }

    });

    private GetResetPassword getResetPassword = new GetResetPassword(new AsyCallBack<GetResetPassword.Info>(){

        @Override
        public void onSuccess(String toast, int type, GetResetPassword.Info info) throws Exception {

            super.onSuccess(toast, type, info);

            if(info.msg.equals("000")){

                registerResult();

            }else {

                UtilToast.show(context,info.msg);

            }
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register2);

        phone = getIntent().getStringExtra("phone");

        account = getIntent().getStringExtra("account");

        login_type = getIntent().getIntExtra("type", 0);

        init_view();
    }

    private void init_view() {

        preferences = getSharedPreferences("tenant", MODE_PRIVATE);

        editor = preferences.edit();

        (title_name = (TextView) findViewById(R.id.tv_title_name)).setText("创建新用户");

        tv_register_1 = (TextView) findViewById(R.id.tv_register_1);

        tv_register_2 = (TextView) findViewById(R.id.tv_register_2);

        tv_register_3 = (TextView) findViewById(R.id.tv_register_3);

        if (login_type == 3) {

            tv_register_2.setText("重置密码");

            tv_register_3.setText("完成");

        } else if (login_type == 1 || login_type == 2) {

            tv_register_1.setText("绑定手机号");

            tv_register_2.setText("设置密码");

            tv_register_3.setText("完成");

        }

        new_pwd = (EditText) findViewById(R.id.et_new_pwd1);

        new_pwd2 = (EditText) findViewById(R.id.et_new_pwd2);

        (clear_pwd1 = (ImageView) findViewById(R.id.iv_clear_pwd1)).setOnClickListener(this);

        (clear_pwd2 = (ImageView) findViewById(R.id.iv_clear_pwd2)).setOnClickListener(this);

        (go_next = (TextView) findViewById(R.id.go_next)).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_clear_pwd1:

                new_pwd.setText("");

                break;

            case R.id.iv_clear_pwd2:

                new_pwd2.setText("");

                break;

            case R.id.go_next:

                pwd_str1 = new_pwd.getText().toString().trim();

                String pwd_str2 = new_pwd2.getText().toString().trim();

                if (pwd_str1.equals("")) {

                    Toast.makeText(this, "请输入新密码", Toast.LENGTH_SHORT).show();

                } else if (pwd_str2.equals("")) {

                    Toast.makeText(this, "请再次输入新密码", Toast.LENGTH_SHORT).show();

                } else if (!pwd_str2.equals(pwd_str1)) {

                    Toast.makeText(this, "两次输入新密码不一致", Toast.LENGTH_SHORT).show();

                } else if (pwd_str1.length() < 6 || pwd_str1.length() > 20) {

                    Toast.makeText(this, "密码位6-20位", Toast.LENGTH_SHORT).show();

                } else {

                    if(login_type == 3) {

                        getResetPassword.phone = phone;

                        getResetPassword.password = pwd_str1;

                        getResetPassword.execute(this);


                    }else {

                        register_net();

                    }

                }

                break;
        }
    }

    private void registerResult(){

            getLoginAdmin.phone = phone;

            getLoginAdmin.password = pwd_str1;

            getLoginAdmin.type = "0";

            getLoginAdmin.execute(context);

    }

    private void register_net() {

        getRegisterUser.phone = phone;

        getRegisterUser.password = pwd_str1;

        getRegisterUser.loginType = String.valueOf(login_type);

        if(login_type == 1){

            getRegisterUser.weChat = account;

        }else if(login_type == 2){

            getRegisterUser.qq = account;

        }

        getRegisterUser.execute(this);

    }


}
